<?php
declare (strict_types = 1);
namespace app\api\controller;

use think\Request;
use app\BaseController;
use think\facade\Db;
use think\exception\ValidateException;

use app\api\validate\GoodsValidate;
use app\api\validate\PointValidate;

use app\api\model\{Users, UserShop, Goods, PointRecord};

class PointController extends BaseController
{
    /**
	 * 积分商品列表
	 */
    public function getPointGoodsLists()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(GoodsValidate::class)->scene('pointList')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $goodsModel = new Goods();

            $where = [
                ['admin_id', '=', $data['admin_id']],
                ['status', '=', 1],
                ['type', '=', 2],
                ['del_time', '=', 0],
            ];

            $field = 'id, title, price, small_img';

            $list = $goodsModel->getList($where, 1, $data['curr'], $data['limit'], $field);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 *兑换
	 */
    public function setExchange()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(PointValidate::class)->scene('add')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $usersModel = new Users();
            $goodsModel = new Goods();
            $userShopModel  = new UserShop();
            $pointRecordModel = new PointRecord();

            // 获取商品信息
            $goodsInfo = $goodsModel->getFind(['id' => $data['goods_id']])['data'];

            if($goodsInfo->getData('type') != 3){
                $this->error_back('商品类型错误');
            }

            // 获取用户信息
            $userInfo = $usersModel->getUserInfo(['id' => $data['user_id']]);

            if($userInfo['user_shop']['point'] < $goodsInfo['price']){
                $this->error_back('积分不足，无法兑换！');
            }

            // 开启事务
            Db::startTrans();

            try{
                $data['price'] = $goodsInfo['price'];
                $flag = $pointRecordModel->add($data);

                if($flag['code'] != 'ok'){
                    $this->error_back($flag['msg']);
                }

                // 用户减去对应积分
                $userShopModel->setDecField(['user_id' => $data['user_id'], 'admin_id' => $userInfo['bind_admin_id']], 'point', $goodsInfo['price']);

                // 写入财务记录
                addFin($data['user_id'], $userInfo['bind_admin_id'], $flag['data'], 2, 2, '-' . $goodsInfo['price'], '兑换' . $goodsInfo['title']);

                // 提交事务
                Db::commit(); 
            }catch(\Exception $e){
                // 回滚事务
                Db::rollback();
            }
            
            $this->success_back('ok', $flag['data']);
        }
    }

    /**
	 * 积分兑换记录列表
	 */
    public function getPointExchangeLists()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(PointValidate::class)->scene('exchangeList')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $pointRecordModel = new PointRecord();

            $where = [
                ['user_id', '=', $data['user_id']],
            ];

            $field = 'id, goods_id, phone, price, status, remarks, create_time, end_time';
            $list = $pointRecordModel->getList($where, 1, $data['curr'], $data['limit'], $field);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $backData = [];
            foreach($list['data'] as $k => $v){
                $backInfo = [
                    'id'          => $v['id'],
                    'title'       => $v['goods_id']['title'],
                    'small_img'   => $v['goods_id']['small_img'],
                    'price'       => $v['price'],
                    'status'      => $v['status'],
                    'remarks'     => $v['remarks'],
                    'create_time' => $v['create_time'],
                    'end_time'    => $v['end_time'],
                ];

                $backData[] = $backInfo;
            }

            $this->success_back('ok', $backData);
        }
    }
}